package com.xiejun.netty;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 回显服务处理器
 */
public class EchoServerHandler implements ChannelHandler {
    
    @Override
    public void channelRead(SocketChannel channel, ByteBuffer buffer) throws IOException {
        // 读取数据
        byte[] data = new byte[buffer.remaining()];
        buffer.get(data);
        String message = new String(data);
        
        System.out.println("EchoServerHandler received: " + message);
        
        // 回写数据
        String response = "Echo: " + message;
        ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
        channel.write(responseBuffer);
    }
    
    @Override
    public void channelConnected(SocketChannel channel) throws IOException {
        System.out.println("Client connected: " + channel.getRemoteAddress());
    }
    
    @Override
    public void channelDisconnected(SocketChannel channel) throws IOException {
        System.out.println("Client disconnected: " + channel.getRemoteAddress());
    }
}